package com.niannian.service;

import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import com.niannian.BaseActivity;
import com.niannian.activity.DateTipActivity;
import com.niannian.activity.DateTipPopping;
import com.niannian.activity.HomeActivity;
import com.niannian.activity.SystemNewsActivity;
import com.niannian.activity.Welcome;
import com.niannian.util.Common;
import com.niannian.util.MessageRecieveManager;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import cn.jpush.android.api.JPushInterface;

/**
 * 自定义接收器
 * 
 * 如果不定义这个 Receiver，则： 1) 默认用户会打开主界面 2) 接收不到自定义消息
 */
public class JpushReceiver extends BroadcastReceiver {
	private static final String TAG = "JPush";

	@Override
	public void onReceive(Context context, Intent intent) {
		Bundle bundle = intent.getExtras();
		Log.d(TAG, "[MyReceiver] onReceive - " + intent.getAction() + ", extras: " + printBundle(bundle));

		if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
			String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
			Log.d(TAG, "[MyReceiver] 接收Registration Id : " + regId);
			// send the Registration Id to your server...

		} else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
			Log.d(TAG, "[MyReceiver] 接收到推送下来的自定义消息: " + bundle.getString(JPushInterface.EXTRA_MESSAGE));
			processCustomMessage(context, bundle);

		} else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
			Log.d(TAG, "[MyReceiver] 接收到推送下来的通知");
			int notifactionId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);
			Log.d(TAG, "[MyReceiver] 接收到推送下来的通知的ID: " + notifactionId);

		} else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
			Log.d(TAG, "[MyReceiver] 用户点击打开了通知");

			// 打开自定义的Activity
			// Intent i = new Intent(context, TestActivity.class);
			// i.putExtras(bundle);
			// i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			// i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
			// Intent.FLAG_ACTIVITY_CLEAR_TOP );
			// context.startActivity(i);

		} else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) {
			Log.d(TAG, "[MyReceiver] 用户收到到RICH PUSH CALLBACK: " + bundle.getString(JPushInterface.EXTRA_EXTRA));
			// 在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码，比如打开新的Activity，
			// 打开一个网页等..

		} else if (JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction())) {
			boolean connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false);
			Log.e(TAG, "[MyReceiver]" + intent.getAction() + " connected state change to " + connected);
		} else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
			// 打开应用
			if (!isRunningForeground(context)) {
				// 清除通知
				JPushInterface.clearAllNotifications(context);
				Intent i = new Intent(context, Welcome.class);
				// i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				context.startActivity(i);
				JPushInterface.reportNotificationOpened(context, bundle.getString(JPushInterface.EXTRA_MSG_ID));
			} else {
				// 清除通知
				JPushInterface.clearAllNotifications(context);
			}
		}

		else {
			Log.d(TAG, "[MyReceiver] Unhandled intent - " + intent.getAction());
		}
	}

	// 打印所有的 intent extra 数据
	private static String printBundle(Bundle bundle) {
		StringBuilder sb = new StringBuilder();
		for (String key : bundle.keySet()) {
			if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
				sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
			} else if (key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)) {
				sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key));
			} else {
				sb.append("\nkey:" + key + ", value:" + bundle.getString(key));
			}
		}
		return sb.toString();
	}

	NotificationManager mNotificationManager;

	NotificationCompat.Builder mBuilder;

	// send msg to MainActivity
	private void processCustomMessage(Context context, Bundle bundle) {
		// if (MainActivity.isForeground) {
		String message = bundle.getString(JPushInterface.EXTRA_MESSAGE);
		String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
		String content_type = bundle.getString(JPushInterface.EXTRA_CONTENT_TYPE);
		// Intent msgIntent = new
		// Intent(MessageRecieveManager.FAMILY_NEWS_UPDATE_ACTION);
		SharedPreferences sp = context.getSharedPreferences("userinfo", Context.MODE_PRIVATE);
		if ("P".equals(content_type)) {
			// try {
			// JSONObject extraJson = new JSONObject(extras);
			// JSONArray jaArray = extraJson.getJSONArray("upcs");
			// for (int i = 0; i < jaArray.length(); i++) {
			// JSONObject jo = jaArray.getJSONObject(i);
			// int fid = jo.getInt("fid");
			// int unc = jo.getInt("unc");
			// if (fid == UserInfoManager.getUserInfoInstance().family) {
			// MessageRecieveManager.FAMILY_NEWS_UPDATE_NUM = unc;
			// Intent msgIntent = new
			// Intent(MessageRecieveManager.FAMILY_NEWS_UPDATE_ACTION);
			// context.sendBroadcast(msgIntent);
			// }
			// }
			// } catch (JSONException e) {
			// // TODO Auto-generated catch block
			// e.printStackTrace();
			// }
		} else if ("R".equals(content_type)) {
			// {"msg_content": "new", "extras": {"count": 2, "sender_avatar":
			// "user_avatar_default1.jpg", "sender": 10000001,
			// "sender_nickname": "9074"}, "content_type": "R"}}

			try {
				// new MsgResetThread(context, bundle).start();

				JSONObject extraJson = new JSONObject(extras);
				String author_avatar = extraJson.getString("sender_avatar");
				String author_nickname = extraJson.getString("sender_nickname");
				int sender = extraJson.getInt("sender");
				int count = extraJson.getInt("count");

				message = count + "条新消息";
				if (sp.getBoolean("notificationsetting", true)) {
					Common.showNotification(sender, context, author_nickname, message, sender, Common.getAvatarThumbs(author_avatar));
				}
			} catch (Exception e) {
				// TODO: handle exception
			}
		} else if ("T".equals(content_type)) {
			try {
				JSONObject extraJson = new JSONObject(extras);

				String title = extraJson.getString("item_content");
				int sender = extraJson.getInt("sender");
				int count = extraJson.getInt("count");

				message = count + "条新提醒";

				if (Common.isAppOnForeground(context)) {
					try {
						BaseActivity.destroyGroup("datetip");
					} catch (Exception e) {

					}

					String item_time = extraJson.getString("item_time");

					Intent intent = new Intent(HomeActivity.activity, DateTipPopping.class);
					intent.putExtra("title", title);
					intent.putExtra("content", message);
					intent.putExtra("id", sender);
					intent.putExtra("item_time", item_time);
					HomeActivity.activity.startActivity(intent);
					Common.showNotification(sender, context, title, message, DateTipActivity.class, sender, "");

				} else {

					if (sp.getBoolean("notificationsetting", true)) {
						Common.showNotification(sender, context, title, message, DateTipActivity.class, sender, "");
					}
				}

			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else if ("S".equals(content_type)) {
			try {
				JSONObject extraJson = new JSONObject(extras);

				String title = extraJson.getString("item_content");
				int sender = extraJson.getInt("sender");
				int count = extraJson.getInt("count");

				message = count + "条新系统消息";
				if (sp.getBoolean("notificationsetting", true)) {
					Common.showNotification(sender, context, "系统消息", title, SystemNewsActivity.class, sender, "");
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}

		try {
			Intent msgIntent = new Intent(MessageRecieveManager.JPUSH_NEWSS_ACTION);
			context.sendBroadcast(msgIntent);
		} catch (Exception e) {
			// TODO: handle exception
		}

	}

	public boolean isRunningForeground(Context context) {
		String packageName = context.getPackageName();
		String topActivityClassName = getTopActivityName(context);
		System.out.println("packageName=" + packageName + ",topActivityClassName=" + topActivityClassName);
		if (packageName != null && topActivityClassName != null && topActivityClassName.startsWith(packageName)) {
			System.out.println("---> isRunningForeGround");
			return true;
		} else {
			System.out.println("---> isRunningBackGround");
			return false;
		}
	}

	public String getTopActivityName(Context context) {
		String topActivityClassName = null;
		ActivityManager activityManager = (ActivityManager) (context.getSystemService(android.content.Context.ACTIVITY_SERVICE));
		List<RunningTaskInfo> runningTaskInfos = activityManager.getRunningTasks(1);
		if (runningTaskInfos != null) {
			ComponentName f = runningTaskInfos.get(0).topActivity;
			topActivityClassName = f.getClassName();
		}
		return topActivityClassName;
	}

}
